package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dto.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.admin.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.net.QCodec;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "参数不能为空");
        }
        if (dto.getArticleId() == null && "".equals(dto.getArticleId())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "参数不能为空");
        }
        //1. 校验参数 文章id必须传
        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if(apBehaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户id和设备id为空");
        }
        //3. 判断阅读行为是否存在
        //根据实体id查询阅读对象
        Query readQuery = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(readQuery, ApReadBehavior.class);
        Update update = new Update();
        if(readBehavior==null){
            //5. 不存在  创建阅读行为 并初始化count字段值为 1
            Short count = 1;
            update.set("count", count).set("updatedTime", new Date());
            //执行修改
            mongoTemplate.updateFirst(readQuery, update, ApReadBehavior.class);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //4. 存在  将阅读行为的count字段加1 并修改
        Short count = (short) (readBehavior.getCount() + 1);
        update.set("count", count).set("updatedTime", new Date());
        //执行修改
        mongoTemplate.updateFirst(readQuery, update, ApReadBehavior.class);

        //添加文章阅读-发送消息
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("阅读行为 发送消息 ==>{}", JSON.toJSONString(mess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
